<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="100px">
      <el-form-item label="商品类目" prop="categoryId">
        <el-cascader filterable v-model="queryParams.categoryId" placeholder="请选择类目" :options="categoryList"
                     :props="{ value: 'id', label: 'name', emitPath: false }" :show-all-levels="false" clearable>
        </el-cascader>
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择资质证书状态" clearable>
          <el-option v-for="dict in dict.type.certificate_status" :key="dict.value" :label="dict.label"
                     :value="dict.value"/>
        </el-select>
      </el-form-item>
      <!--      <el-form-item label="资质信息key" prop="quailficationKey">-->
      <!--        <el-input v-model="queryParams.quailficationKey" placeholder="请输入资质信息key" clearable-->
      <!--                  @keyup.enter.native="handleQuery"/>-->
      <!--      </el-form-item>-->
      <el-form-item label="方案名称" prop="memo">
        <el-input v-model="queryParams.memo" placeholder="请输入方案名称" clearable @keyup.enter.native="handleQuery"/>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button type="primary" size="mini" @click="handleAdd">新增</el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button size="mini" type="success" @click="syncQualificationInfo">批量同步资质信息</el-button>
      </el-col>

      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="success"-->
      <!--          plain-->
      <!--          icon="el-icon-edit"-->
      <!--          size="mini"-->
      <!--          :disabled="single"-->
      <!--          @click="handleUpdate"-->
      <!--        >修改-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="danger"-->
      <!--          plain-->
      <!--          icon="el-icon-delete"-->
      <!--          size="mini"-->
      <!--          :disabled="multiple"-->
      <!--          @click="handleDelete"-->
      <!--          v-hasPermi="['gather:collectProductQualifications:remove']"-->
      <!--        >删除-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <!--      <el-col :span="1.5">-->
      <!--        <el-button-->
      <!--          type="warning"-->
      <!--          plain-->
      <!--          icon="el-icon-download"-->
      <!--          size="mini"-->
      <!--          @click="handleExport"-->
      <!--          v-hasPermi="['gather:collectProductQualifications:export']"-->
      <!--        >导出-->
      <!--        </el-button>-->
      <!--      </el-col>-->
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="collectProductQualificationsList" @selection-change="handleSelectionChange"
              border stripe>
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="方案名称" align="center" prop="memo"/>
      <el-table-column label="类目名称" align="center" prop="categoryName"/>
      <el-table-column label="资质类型" align="center" prop="type" width="100">
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.detailsList" :key="index">
            {{ item.type }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="资质信息key" align="center" prop="qualificationKey" width="300">
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.detailsList" :key="index">
            {{ item.key }}
          </div>
        </template>
      </el-table-column>
      <el-table-column label="详情内容" align="center" prop="value">
        <template slot-scope="scope">
          <div v-for="(item,index) in scope.row.detailsList">
            <div v-if="item.type == 'image'">
              <image-preview v-if="item.value" :src="item.value" width="60px" height="60px"></image-preview>
            </div>
            <div v-else>{{ scope.row.value }}</div>
          </div>
        </template>
      </el-table-column>
      <el-table-column label="状态" align="center" prop="status">
        <template slot-scope="scope">
          <dict-tag :options="dict.type.certificate_status" :value="Number(scope.row.status)"></dict-tag>
        </template>
      </el-table-column>
      <!--      <el-table-column label="关联产品" align="center" prop="collectProductId" width="120">-->
      <!--        <template slot-scope="scope">-->
      <!--          <div class="text-blue changeHand" @click="openBindProductModal(scope.row)">查看关联产品</div>-->
      <!--        </template>-->
      <!--      </el-table-column>-->
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="120">
        <template slot-scope="scope">
          <el-button size="mini" type="text" @click="handleUpdate(scope.row)">修改</el-button>
          <el-button size="mini" type="text" @click="handleDelete(scope.row)">删除</el-button>
          <el-button size="mini" type="text" @click="viewTask(scope.row)">查看任务</el-button>
          <!--          <el-button size="mini" type="text" @click="toExamine(scope.row)">确认审核</el-button>-->
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改商品资质信息对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="800px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="200px">
        <el-form-item label="方案名称" prop="memo">
          <el-input v-model="form.memo" size="small" placeholder="请输入方案名称"/>
        </el-form-item>
        <el-form-item label="要求" prop="requireMemo">
          <el-input v-model="form.requireMemo" type="textarea" :autosize="{ minRows: 2, maxRows: 10}"
                    placeholder="请输入要求内容"/>
        </el-form-item>
        <el-form-item label="商品类目" prop="categoryId">
          <el-cascader filterable v-model="form.categoryId"
                       placeholder="请选择类目"
                       :options="categoryList"
                       :props="{ value: 'id', label: 'name', emitPath: false }" :show-all-levels="false" clearable
                       @change="getCategoryInfo" @clearCheckedNodes="clearCheckedNodes">
          </el-cascader>
        </el-form-item>
        <el-form-item v-for="(item,index) in quailficationInfoList" :key="index" :label="item.label">
          <div v-if="item.type=='image'">
            <image-upload v-model="item.value" :changeSize="true" :limit="1" :is-show-tip="false" width="50px"
                          height="50px"/>
            <span class="text-danger fontSize12">{{ item.tips }}</span>
          </div>
          <div v-else>
            <el-input v-model="item.value" placeholder="请输入资质信息id"/>
          </div>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button v-if="quailficationInfoList&&quailficationInfoList.length>0" :loading="buttonLoading" type="primary"
                   @click="submitForm">确 定
        </el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
    <!-- 公共采集库导入 -->
    <el-dialog title="资质证书绑定商品" :visible.sync="isImport" width="80%" :show-close="false" center>
      <div class="edit-box">
        <DialogList v-if="isImport" ref="dialoglist" :certificateInfo="certificateInfo"/>
      </div>
      <div slot="footer" class="dialog-footer">
        <!--        <el-button :disabled="pubLoading" type="primary" plain @click="confirmBindProduct">确 定</el-button>-->
        <el-button :disabled="pubLoading" @click="closeIsImport">取 消</el-button>
      </div>
    </el-dialog>
    <taskListComponent v-if="isOpenTaskListModal" :programId="programId"
                       @close="closeTaskListModal"></taskListComponent>
  </div>
</template>

<script>
import {
  listCollectProductQualifications,
  getCollectProductQualifications,
  delCollectProductQualifications,
  addCollectProductQualifications,
  selectQuailficationByCategoryId,
  bindingQualifications,
  synchronizationProgram
} from "@/api/certificate/certificate";
import {selectlistCollectProductCategory} from "@/api/gather/collectProductCategory";
import dialogList from "@/views/certificate/components/dialogList.vue";
import {addToSellerPro} from "@/api/persongather/collectProduct";
import taskListComponent from "@/views/certificate/components/task-list-component.vue";

export default {
  name: "CollectProductQualifications",
  dicts: ['is_bind_qualification_info', 'certificate_status'],
  components: {
    DialogList: dialogList,
    taskListComponent
  },
  data() {
    return {
      isImport: false,//是否打开公共采集库导入弹窗
      pubLoading: false,//导入loading
      // 按钮loading
      buttonLoading: false,
      // 遮罩层
      loading: true,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 商品资质信息表格数据
      collectProductQualificationsList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        categoryId: undefined,
        categoryQualificationId: undefined,
        quailficationKey: undefined,
        details: undefined,
        collectProductId: undefined,
        memo: undefined,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        categoryId: [
          {required: true, message: "类目id不能为空", trigger: "blur"}
        ],
        categoryQualificationId: [
          {required: true, message: "类目资质类型id不能为空", trigger: "blur"}
        ],
        value: [
          {required: true, message: "提交信息不能为空", trigger: "blur"}
        ],
        collectProductId: [
          {required: true, message: "关联产品不能为空", trigger: "blur"}
        ],
        memo: [
          {required: true, message: "备注不能为空", trigger: "blur"}
        ],
      },
      categoryList: [],//商品类目
      quailficationInfoList: [],// 填写资质信息列表
      certificateInfo: {},//组件传入的证书信息
      isOpenTaskListModal: false,//是否打开定时任务列表
      programId: '',//方案id
    };
  },
  created() {
    this.getList();
    this.getGoodsCategory()
  },
  methods: {
    // 导入到公共采集库
    confirmBindProduct() {
      const ids = (this.$refs.dialoglist.ids).toString();
      if (ids) {
        this.$modal.confirm('是否将商品编号为"' + ids + '"的数据导入个人采集库？').then(() => {
          this.pubLoading = true;
          const params = {
            collectProductId: ids,
            programId: this.certificateInfo.qualificationsId
          }
          bindingQualifications(params).then(res => {
            this.pubLoading = false;
            this.getList();
            this.isImport = false;
            this.$modal.msgSuccess(res.msg);
            this.$refs.dialoglist.resetQuery();
          })
        })
      } else {
        this.$modal.msgError("请先选择商品！");
      }
    },
    // 公共产品库导入打开弹框
    openBindProductModal(row) {
      this.certificateInfo = {
        qualificationsId: row.id,
        type: '1',
        categoryId: row.categoryId,
        pageNum: 1,
        pageSize: 10,
        isBindingQualifications: '1'
      }
      this.isImport = true;
    },
    // 关闭导入弹窗
    closeIsImport() {
      this.$refs.dialoglist.resetQuery();
      this.isImport = false;
      // this.$refs.queryForm
    },
    // 商品类目
    getGoodsCategory() {
      selectlistCollectProductCategory().then(response => {
        this.categoryList = this.handleTree(response.data, "id", "parentId");
      });
    },
    // 清空类目选中节点
    clearCheckedNodes(e) {
      console.log('eee', e)
    },
    /** 查询商品资质信息列表 */
    getList() {
      this.loading = true;
      listCollectProductQualifications(this.queryParams).then(response => {
        let list = response.rows
        list.forEach((val, index, arr) => {
          let detailsList = JSON.parse(val.details)
          list[index]['detailsList'] = detailsList
        })
        this.collectProductQualificationsList = list;
        console.log('&&&', this.collectProductQualificationsList)
        this.total = response.total;
        this.loading = false;
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        // categoryId: undefined,
        // categoryQualificationId: undefined,
        // value: undefined,
        // memo: undefined,
        categoryId: undefined,
        categoryQualificationId: undefined,
        memo: undefined,
        // value: undefined,
        detailsList: []
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      console.log(this.form)
      this.open = true;
      this.form.operationType = '0'
      this.title = "添加商品资质信息";
      this.quailficationInfoList = []
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCollectProductQualifications(id).then(response => {
        this.loading = false;
        this.quailficationInfoList = response.data.qualificationVoList;
        this.form = response.data;
        this.open = true;
        this.form.operationType = '1'
        this.title = "修改商品资质信息";
        this.getCategoryInfo(this.form.categoryId, 'isEdit')
      });
    },
    // 选择类目
    getCategoryInfo(e, type) {
      console.log('选择类目', e)
      selectQuailficationByCategoryId({categoryId: e}).then(res => {
        let list = res.data
        for (let i = 0; i < list.length; i++) {
          list[i]['value'] = ''
        }

        var resMap = new Map();
        res.data.forEach(item => {
          item.show = true;
          resMap.set(item.qualificationKey, item);
        })

        this.quailficationInfoList.forEach(item => {
          var attribute = resMap.get(item.qualificationKey)
          if (attribute == undefined) {
            item.show = false;
            resMap.set(item.qualificationKey, item);
          } else {
            attribute.value = item.value;
          }
        });
        // }
        var attr = [];
        resMap.forEach((key, val) => {
          attr.push(key);
        });
        this.quailficationInfoList = attr;
      })
    },
    /** 提交按钮 */
    submitForm() {
      console.log('上传的商品信息', this.form, this.quailficationInfoList)
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.buttonLoading = true;

          let valueList = [], list = this.quailficationInfoList, newList = this.newCertificateList;
          // valueList = [...list, ...newList]
          for (let i = 0; i < list.length; i++) {
            valueList.push({
              "id": list[i].id,
              "type": list[i].type,
              "key": list[i].qualificationKey,
              "value": list[i].value
            })
          }
          // console.log('valueList', valueList)
          this.form.detailsList = valueList

          addCollectProductQualifications(this.form).then(response => {
            this.$modal.msgSuccess(response.msg);
            this.open = false;
            this.getList();
          }).finally(() => {
            this.buttonLoading = false;
          });
          // }
        }
      });
    },
    // 同步资质信息
    syncQualificationInfo(row) {
      this.$confirm("是否确定同步资质信息？").then(() => {
        let id = this.ids.toString()
        synchronizationProgram({programId: id}).then(res => {
          this.$message.success(res.msg)
          this.getList()
        })
      })
    },
    // 审核资质信息
    toExamine(row) {
      this.loading = true;
      this.reset();
      const id = row.id || this.ids
      getCollectProductQualifications(id).then(response => {
        this.loading = false;
        this.quailficationInfoList = response.data.qualificationVoList;
        this.form = response.data;
        this.form.operationType = '3'
        this.open = true;
        this.title = "审核商品资质信息";
        this.getCategoryInfo(this.form.categoryId, 'isEdit')
      });
    },
    // 关闭任务列表
    closeTaskListModal() {
      this.isOpenTaskListModal = false
    },
    // 查看定时任务执行情况
    viewTask(row) {
      this.programId = row.id
      this.isOpenTaskListModal = true
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$modal.confirm('是否确认删除商品资质信息编号为"' + ids + '"的数据项？').then(() => {
        this.loading = true;
        return delCollectProductQualifications(ids);
      }).then(() => {
        this.loading = false;
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {
      }).finally(() => {
        this.loading = false;
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      this.download('gather/collectProductQualifications/export', {
        ...this.queryParams
      }, `collectProductQualifications_${new Date().getTime()}.xlsx`)
    }
  }
};
</script>
